<?php

namespace backend\controllers;

use Yii;
use backend\models\Category;
use backend\models\CategorySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

use yii\web\Response;
use yii\bootstrap\ActiveForm;

/**
 * CategoryController implements the CRUD actions for Category model.
 */
class CategoryController extends Controller {

    private $model;
    
    private $ajaxMessage = array(
        'error'=>'0',
        'message'=>"",
        'content'=>'',
    );
    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function init() {
        parent::init();
        $this->model = new Category();
    }

    /**
     * Lists all Category models.
     * @return mixed
     */
    public function actionIndex() {
        
        $searchModel = new CategorySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $data = $this->GetCategoryTree();

        if (count($data) > 0) {
            $models = $dataProvider->getModels();

            $sortList = array();
            foreach ($models as $k => $v) {

                foreach ($data as $key => $value) {

                    if (preg_replace("/[└|╍]*?/u", "", $value['title']) == $v->title) {
                        $v->title = $value['title'];
                        $sortList[$k] = $key;
                    }
                }
            }

            $modelsSorted = array();
            //更新 Key
            foreach ($sortList as $k => $v) {

                $modelsSorted[$v] = $models[$k];
            }

            ksort($modelsSorted);

            $dataProvider->setModels($modelsSorted);
        }




        return $this->render('index', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
                     'model' => $this->model,
            'data' => $this->GetCategoryTree(),
        ]);
    }

    /**
     * Displays a single Category model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id) {
        return $this->render('view', [
                    'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Category model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $this->layout = false;
       
//        Yii::$app->response->format=Response::FORMAT_JSON;
        
        
        
        if (!Yii::$app->request->isPost) {

            //渲染模板
            return $this->render('create', [
                        'model' => $this->model,
                        'data' => $this->GetCategoryTree(),
            ]);
        } else {
            
            
            
            if ($this->model->load(Yii::$app->request->post()) && $this->model->save()) {

                Yii::$app->session->setFlash("success","类目创建成功");
                
                return $this->redirect(\yii\helpers\Url::toRoute("/category/index"));
            } else {
                
               Yii::$app->session->setFlash("error","添加失败,请检测标题和标识 不能重复，而且不能为空");
                
                return $this->redirect(\yii\helpers\Url::toRoute("/category/index"));
               
            }
        }
    }

    /**
     * Updates an existing Category model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id) {

      
        $this->layout = false;
        $model = $this->findModel($id);

        
        if(Yii::$app->request->isPost){
            
            if($model->load(Yii::$app->request->post()) && $model->save(false)){
                
                Yii::$app->session->setFlash("success","更新成功");
            }else{
                Yii::$app->session->setFlash("error","更新失败");
            }
            
            return $this->redirect(\yii\helpers\Url::toRoute("/category/index"));
            
        }else{
            return $this->render('update', [
                    'model' => $model,
                    'data' => $this->GetCategoryTree(),
                    'nameAttribute' => $model->title,
                ]);
            
        }
   

        
        
        

    }

    /**
     * Deletes an existing Category model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id) {
        
        $this->enableCsrfValidation = false;
        
//        Yii::$app->response->format=Response::FORMAT_JSON;
        
        $message = array();
        $tag = "success";
        if($this->model->hasChildren($id)){
            $message[] = "该类目下还有子分类";
            $tag = "error";
        }else{
             if(!$this->findModel($id)->delete()){
                 $message[] = "删除失败 ";
                 $tag = "error";
             }   
            
             $message[] =  "类目删除成功";
        }
            
        Yii::$app->session->setFlash($tag,  implode(",", $message));
        return $this->redirect(\yii\helpers\Url::toRoute("/category/index"));
    }

    /**
     * Finds the Category model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Category the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = Category::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    /**
     * 
     *   数据验证方法 
     *   
     * 
     * 
     * * */
    public function validate() {

        $model = new Category();
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
    }

    public static function GetCategoryTree() {


        $data = array();
        $condition = array(
                // 'status'=>1,
        );
        $data = Category::find()->andWhere($condition)->asArray()->all();

        $data = self::CategoryTree($data,"pid");

        $data = self::CategoryTree2parr($data,"title");


        return $data;
    }

    public static function CategoryTree($arr,$parentVar) {

        $count = count($arr);
        if ($count < 1)
            return $arr;

        foreach ($arr as $k => $v) {
            if ($v[$parentVar] == 0)
                continue;
            //寻找父节点所在的位置
            foreach ($arr as $key => $value) {

                if ($v[$parentVar] == $value['id']) {
                    $arr[$key]['children'][] = &$arr[$k];  //灵活地使用了引用
                    break;
                }
            }unset($key);
            unset($value);
        }

        //清除掉不是父分级的
        foreach ($arr as $key => $value) {

            if ($value[$parentVar] != 0) {
                unset($arr[$key]);
            }
        }

        return $arr;
    }

    /*
     * 把分类 tree 形 数组  变回为 平铺数组  
     * array  $arr
     * string $whilespace indent符号 
     * int $wspaceNum
     * 
     * $relateField  perent_id 字段名
     * * */

    public static function CategoryTree2parr($arr,$var = "title", $wspace = "╍", $wspaceNum = 2) {

        
        $deep = 0;
        static $result;
        static $deep;  //递归深度
        $nodeStartStr = "└";

        $deep++;
        if (!is_array($arr))
            return $arr;


        foreach ($arr as $k => $v) {

            $v[$var] = ($deep > 1 ? $nodeStartStr : "") . str_repeat($wspace, ($deep - 1) * $wspaceNum) . $v[$var];
            $result[] = $v;
            if (isset($v['children']) && is_array($v['children'])) {

                self::CategoryTree2parr($v['children'],$var);
            }
        }

        $deep--;

        return $result;
    }
    
    
    
    //该方法是异步校验字段，输入框失去焦点之后自动会自动请求改地址
    public function actionValidate(){
        $model = new PostModel();
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {        
            Yii::$app->response->format = Response::FORMAT_JSON;        
            return ActiveForm::validate($model);
        }
    }
    
    
    



    

}
